<template>
	<div class="home">
		<header class="header">
			<div class="city" @click="state.areaShow = true">
				<van-icon color="#555555" name="location" size="16" />
				<span style="font-size: 16px">{{ state.currentCity || '全国' }}</span>
				<van-icon class="play" color="#a5a5a5" name="play" size="14" />
			</div>
			<div class="tabs">
				<van-tabs
            swipeable
					v-model:active="state.active"
					line-width="30px"
					title-inactive-color="#A6A6A6"
					title-active-color="#333333"
					:before-change="tabsBeforeChange"
				>
					<van-tab v-for="item of state.tabs" :name="item" :title="item" />
				</van-tabs>
			</div>
			<div>

        <van-dropdown-menu
            active-color="#f54386"
           :close-on-click-overlay="!state.closeDropdownOverlayMenu"
           :close-on-click-outside="state.closeDropdownOutsideMenu"
        >
          <van-dropdown-item title="筛选条件" ref="dropdownItemRef"  @closed="closeDropdownMenu">
            <van-field name="state.searchOptions.sex" label="性别">
              <template #input>
                <van-radio-group v-model="state.searchOptions.sex" direction="horizontal">
                  <van-radio style="margin-right: 20px" name="">全部</van-radio>
                  <van-radio style="margin-right: 20px" name="男">男</van-radio>
                  <van-radio style="margin-right: 15px" name="女">女</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            <div v-if="state.moreSearchWhere" class="more">
              <van-cell title="年龄" is-link :value="state.searchOptions.age" @click="cellClick('年龄')" />
              <van-cell title="月收入" is-link :value="state.searchOptions.income" @click="cellClick('月收入')" />
              <van-cell title="所在地区" is-link :value="state.currentCity" @click="cellClick('所在地区')" />
              <van-cell title="学历" is-link :value="state.searchOptions.educate" @click="cellClick('学历')" />
              <van-cell title="婚姻状况" is-link :value="state.searchOptions.marriage" @click="cellClick('婚姻状况')" />
              <van-cell title="身高" is-link :value="`${state.searchOptions.height}${state.searchOptions.height ? 'cm' : ''}`" @click="cellClick('身高')" />
              <van-cell title="体重" is-link :value="`${state.searchOptions.weight}${state.searchOptions.weight ? 'kg' : ''}`" @click="cellClick('体重')" />
              <van-field name="state.searchOptions.is_children" label="有无孩子">
                <template #input>
                  <van-radio-group v-model="state.searchOptions.is_children" direction="horizontal">
                    <van-radio style="margin-right: 20px" name="">全部</van-radio>
                    <van-radio style="margin-right: 20px" name="有">有</van-radio>
                    <van-radio style="margin-right: 15px" name="无">无</van-radio>
                  </van-radio-group>
                </template>
              </van-field>
              <van-field name="state.searchOptions.want_children" label="是否想要孩子">
                <template #input>
                  <van-radio-group v-model="state.searchOptions.want_children" direction="horizontal">
                    <van-radio style="margin-right: 20px" name="">全部</van-radio>
                    <van-radio style="margin-right: 20px" name="想">想</van-radio>
                    <van-radio name="不想">不想</van-radio>
                  </van-radio-group>
                </template>
              </van-field>
              <van-field name="state.searchOptions.is_house" label="是否有房">
                <template #input>
                  <van-radio-group v-model="state.searchOptions.is_house" direction="horizontal">
                    <van-radio style="margin-right: 20px" name="">全部</van-radio>
                    <van-radio style="margin-right: 20px" name="有">有</van-radio>
                    <van-radio style="margin-right: 15px" name="无">无</van-radio>
                  </van-radio-group>
                </template>
              </van-field>
              <van-field name="state.searchOptions.is_car" label="是否有车">
                <template #input>
                  <van-radio-group v-model="state.searchOptions.is_car" direction="horizontal">
                    <van-radio style="margin-right: 20px" name="">全部</van-radio>
                    <van-radio style="margin-right: 20px" name="有">有</van-radio>
                    <van-radio style="margin-right: 15px" name="无">无</van-radio>
                  </van-radio-group>
                </template>
              </van-field>
            </div>
            <div v-else class="tips" style="padding: 20px 0;text-align: center;font-size: 14px;">
              <span style="color: #969AA0">点击</span>
              <span style="color: #f54386">精选</span>
              <span style="color: #969AA0">展现更多筛选条件</span>
            </div>
            <div style="padding: 5px 16px;display: flex;flex-direction: row;">
              <van-button type="warning" style="margin-right: 10px" block round size="small" @click="onResetSearch">重置</van-button>
              <van-button type="danger" style="margin-right: 10px;background-color: #3775E1;border-color: #3775E1;" block round size="small" @click="onMoreSearch">精选</van-button>
              <van-button type="danger" style="background-color: #f54386;border-color: #f54386;" block round size="small" @click="onConfirm">确认选择</van-button>
            </div>
          </van-dropdown-item>
        </van-dropdown-menu>
			</div>
		</header>

		<main class="my_swiper_box">
			<swiper
				class="my_swiper"
				direction="vertical"
				:spaceBetween="15"
				:modules="[Virtual]"
				virtual
				@slideChange="onSlideChange"
			>
				<template v-for="(item, index) of state.menberList" :key="item.id">
					<swiper-slide class="swipe_item">
						<!-- 视频 -->
						<MyVideoPlay
							v-if="item.is_vip_video && item.vcr.video_url"
							:ref="(el) => setItemRef(el, item.id)"
							:item="item"
              :page="state.module"
							@videoClick="videoClick(item.user_id)"
						/>
						<!-- 图片 -->
						<img class="img" v-else v-lazy="imgUrl + item.user_img" />

						<!-- 用户信息 -->
						<div class="user_info">
							<div>
								<span>{{ item.username }}</span>
								<img v-if="showVip(item)" class="vip" src="@/assets/img/vip_icon.png" />
								<img v-if="item.is_vip_video" class="certification" src="@/assets/img/certification_icon.png" />
							</div>
							<p class="info">{{ item.age }}岁 {{ item.height }}cm {{ item.job }} {{ item.income }}</p>
							<p>{{ item.province }} {{ item.city }}</p>
						</div>
						<!-- 头像 -->
						<van-image
							class="avatar"
							round
							width="45px"
							height="45px"
							fit="cover"
							:src="getUserHeadImg(item)"
							@click="avatarClick(item.user_id)"
						/>

						<!-- 收藏 -->
						<div class="share collection" v-debounce="() => collect(item.user_id, index)">
							<img v-if="item.is_collect" src="@/assets/img/video/collectionActive_icon.png" />
							<img v-else src="@/assets/img/video/collection_icon.png" />
							<span>{{ item.like_num }}</span>
						</div>
						<!-- 分享 -->
						<div class="share" @click="state.codeDialogShow = true">
							<img src="@/assets/img/video/share_icon.png" />
							<span>{{ item.share_num }}</span>
						</div>
						<!-- 电话 -->
						<a class="tel" :href="state.mobile" v-debounce="() => callMobile(item.mobile)">
							<img src="@/assets/img/tel_icon.png" />
						</a>
            <span class="tel_bottom_text">牵线</span>
					</swiper-slide>
				</template>
			</swiper>
		</main>

		<MyTabbar />

		<!-- 开通套餐会员弹窗 -->
		<vipPopup ref="vipPopupRef" @openVipPackage="openVipPackage" />

		<!-- 一元付费弹窗 -->
		<MyDialogBtn v-model:show="state.payShow" column>
			<template #content>
<!--				<div>观看本视频需付费一元 观看，或成为平台VIP用户即可 享受全部免费观看！</div>-->
				<div>观看本视频需付费一元</div>
			</template>
			<template #btn>
				<van-button type="primary" @click="payOneYuan">付费一元</van-button>
<!--				<van-button type="success" @click="becomeVip">成为VIP</van-button>-->
				<van-button type="success" @click="state.payShow = false">取消</van-button>
			</template>
		</MyDialogBtn>

		<!-- 认证会员弹窗 -->
		<MyDialogBtn v-model:show="state.vipShow">
			<template #content>
				<div>是否需要栏目认证？</div>
			</template>
			<template #btn>
				<van-button type="primary" @click="jumpVideoAuth">去了解</van-button>
				<van-button type="success" @click="state.vipShow = false">再看看</van-button>
			</template>
		</MyDialogBtn>

    <!-- 分享说明 -->
    <MyDialogBtn v-model:show="state.codeDialogShow" column>
      <template #content>
        <div style="max-height: 50vh; overflow: scroll">
          <div style="margin-bottom: 30px">分享说明</div>
          <p v-html="state.promote_contents" style="font-size: 13px; text-align: left; line-height: 24px"></p>
        </div>
      </template>
      <template #btn>
        <van-button type="primary" @click="state.codeDialogShow = false">确定</van-button>
      </template>
    </MyDialogBtn>

    <!-- 选择器弹窗 -->
    <MyPopupPicker ref="popupPickerRef" :popupTitle="state.popupTitle" @popupConfirm="popupConfirm">
      <van-datetime-picker
          v-if="state.currentPickerTitle === '生日'"
          ref="datetimePickerRef"
          type="date"
          v-model="state.birthdayValue"
          :show-toolbar="false"
          :min-date="state.minDate"
          :max-date="state.maxDate"
          @confirm="datetimePickerConfirm"
      />
      <van-area
          v-else-if="state.currentPickerTitle === '所在地区'"
          :area-list="areaList"
          :value="state.areaDefaultCode"
          columns-num="2"
          :columns-placeholder="['全部', '全部']"
          @change="areaChange"
      >
        <template #confirm></template>
        <template #cancel></template>
      </van-area>
      <van-picker
          v-else
          ref="pickerRef"
          :columns="state.columns"
          :default-index="state.defaultIndex"
          :show-toolbar="false"
          @confirm="pickerConfirm"
      />
    </MyPopupPicker>

		<van-popup v-model:show="state.areaShow" round position="bottom">
			<van-area
          :area-list="areaList"
          :value="state.areaDefaultCode"
          columns-num="2"
          :columns-placeholder="['全部', '全部']"
          @confirm="areaConfirm"
          @cancel="state.areaShow = false" />
		</van-popup>
	</div>
</template>

<script setup lang="ts">
import {ComponentPublicInstance, computed, nextTick, onActivated, onMounted, reactive, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {Virtual} from 'swiper';
import {Swiper, SwiperSlide} from 'swiper/vue';
import type {Swiper as SwiperClass} from 'swiper/types';
import {
  addUser,
  bindUserRelate,
  editUser,
  getAddressByGPS,
  getWxConfig,
  memberInfo,
  opendIdByCode,
  wxPay,
  wxVipPay
} from '@/api/common';
import {
  checkUserStateByOneYuan,
  createOneYuanOrder,
  createVipOrder,
  memberList,
  saveBrowseRecord,
  saveCollect,
  updateShareCount
} from '@/api/index';
import {getQueryString} from '@/utils/util';

import {useMainStore} from '@/store';
import useAuthorize from '@/hooks/authorize';
import wxApiReady from '@/hooks/wxApiReady';
import showVip from '@/hooks/showVip';
import MyTabbar from '@/components/MyTabbar.vue';
import MyVideoPlay from '@/components/MyVideoPlay.vue';
import MyDialogBtn from '@/components/MyDialogBtn.vue';
import vipPopup from './components/vipPopup.vue';
import type {AreaColumnOption, DropdownItemInstance, DropdownItemOption, ToastOptions} from 'vant';
import {DatetimePickerInstance, PickerInstance, PickerOption, Toast} from 'vant';
import {areaList} from '@vant/area-data';
import wx from 'weixin-jsapi';
import MyPopupPicker from "@/components/MyPopupPicker.vue";
import {formatDate} from "@/utils/formatTime";

const imgUrl = import.meta.env.VITE_IMG_URL;
const siteTitle = import.meta.env.VITE_SITE_TITLE;
const siteDomain = import.meta.env.VITE_DOMAIN;
const mainStore = useMainStore();
const router = useRouter();
const route = useRoute();
const state = reactive<any>({
  module:'member',//普通用户与VIP用户
	showFlag: true,
	areaShow: false,
	searchShow: false,
	areaDefaultCode: '110101',
  codeDialogShow: false,
  promote_contents:'点击右上角【...】分享到朋友圈或微信群：<br/>' +
      '①可成为注册会员推荐人；<br/>' +
      '②获得视频付费观看40%收益。',
	mobile: 'javascript:;',
	pageInfo: {
		pageIndex: 1,
		pageSize: 50,
		user_id: mainStore.user_id,
		city: null,
    province: null,
		is_vip_video: null,
		share_user_id: route.query.share_user_id || '',
		state: 1,
    form:[]
	},
	sexOption: [
		{ text: '查看全部', value: '' },
		{ text: '只看男性', value: '男' },
		{ text: '只看女性', value: '女' }
	],
	payShow: false,
	vipShow: false,
	active: 0,
	tabs: ['全国', '同城', '栏目认证'],
	currentIndex: 0,
  currentCity: null,
	menberList: [] as any[],

	province: '',
	city: '',
	country: '',

  closeDropdownOverlayMenu:false,
  closeDropdownOutsideMenu:false,
  pickerDate: {
    性别: { title: '选择性别', key: 'sex', index: 0, list: ['男', '女'] },
    年龄: {
      title: '选择年龄',
      key: 'age',
      index: 0,
      list: ['不限', '18~25','26~30', '31~35','36~40','41~45','46~50','51~55','56~60','61~70','71~75','76~80','81~85','86~90','91~95','95~100']
    },
    月收入: {
      title: '选择月收入',
      key: 'income',
      index: 0,
      list: ['不限', '0~3000', '3000~6000', '6000~8000', '10000~15000', '20000以上']
    },
    学历: {
      title: '选择学历',
      key: 'educate',
      index: 0,
      list: ['不限', '小学', '初中', '高中', '专科', '本科', '研究生']
    },
    婚姻状况: { title: '选择婚姻状况', key: 'marriage', index: 0, list: ['不限', '未婚', '离异', '丧偶', '意向红娘', '意向月老'] },
    身高: {
      title: '选择身高cm',
      key: 'height',
      index: 0,
      list: ['不限', '140~149', '150~159', '160~169','170~179','180~189','190~199','200~209']
    },
    体重: {
      title: '选择体重kg',
      key: 'weight',
      index: 0,
      list: ['不限', '30~39','40~49','50~59','60~69','70~79','80~89','90~99','100~109','110~119','120~129','130~139','140~149','150~159']
    },
    体型: { title: '选择体型', key: 'shape', index: 1, list: ['偏瘦', '正常', '偏胖'] },
    有无孩子: { title: '选择有无孩子', key: 'is_children', index: 0, list: ['无', '有'] },
    是否想要孩子: { title: '选择是否想要孩子', key: 'want_children', index: 0, list: ['不想', '想'] },
    是否有房: { title: '选择是否有房', key: 'is_house', index: 0, list: ['无', '有'] },
    是否有车: { title: '选择是否有车', key: 'is_car', index: 0, list: ['无', '有'] },
  },

  columns: [],
  defaultIndex: 0,
  currentPickerTitle: '',
  popupTitle: '',
  minDate: new Date(1950, 0, 17),
  maxDate: new Date(),
  birthdayValue: new Date(),
  areaValue: '',
  moreSearchWhere:false,
  dropdownItem:ref(null),
  searchOptions : {
    sex:'',
    age:'',
    income:'',
    educate:'',
    height:'',
    weight:'',
    is_children:'',
    want_children:'',
    is_house:'',
    is_car:'',
    province: '',
    city: '',
    area: '',
    marriage: '',
  }
});

// 跳转视频认证页面
const jumpVideoAuth = () => {
  state.vipShow = false;
  router.push({ name: 'verifiedMember' })
}

// 城市改变
const areaChange = (areaColumn: AreaColumnOption[]) => {
  const province = areaColumn[0].name;
  const city = areaColumn[1].name;
  const area = '';//areaColumn[2].name;
  if (city != '') {
    state.currentCity = city;
  } else {
    state.currentCity = province;
  }
  state.areaValue = province + city + area;
  Object.assign(state.searchOptions, { province, city , area});
};

// 生日picker确认方法
const datetimePickerConfirm = (currentValue: PickerOption | PickerOption[], currentIndex: number | number[]) => {
  state.form.birthday = formatDate(new Date(state.birthdayValue), 'YYYY-mm-dd');
};

// picker确认方法
const pickerConfirm = (currentValue: PickerOption | PickerOption[], currentIndex: number | number[]) => {
  const pickerDate = state.pickerDate[state.currentPickerTitle];
  state.searchOptions[pickerDate.key] = currentValue;
  pickerDate.index = currentIndex;
};

// picker确认按钮
const datetimePickerRef = ref<DatetimePickerInstance | null>(null);
const pickerRef = ref<PickerInstance | null>(null);
const popupConfirm = (): void => {
  if (state.currentPickerTitle === '生日') {
    datetimePickerRef.value?.getPicker().confirm();
  }
  if (state.currentPickerTitle === '所在地区' && !state.areaValue) {
    // 城市默认值
    state.searchOptions.province = '北京市';
    state.searchOptions.city = '北京市';
    state.searchOptions.area = '东城区';
    state.areaValue = '北京市北京市东城区';
    return;
  }
  pickerRef.value?.confirm();
};

// 选项点击
const popupPickerRef = ref<InstanceType<typeof MyPopupPicker> | null>(null);
const cellClick = (title: string): void => {
  state.currentPickerTitle = title;

  if (title === '生日' || title === '所在地区') {
    state.popupTitle = `选择${title}`;
    popupPickerRef.value!.show();
    return;
  }

  const currentPicker = state.pickerDate[title];
  state.popupTitle = currentPicker.title;

  // 选择器内容
  state.columns = currentPicker.list;

  // 选择器默认索引
  state.defaultIndex = currentPicker.index;
  popupPickerRef.value!.show();
};

// 关闭下拉框
const closeDropdownMenu = () => {
  state.moreSearchWhere = false;
}
// 确认选择
const onConfirm = () => {
  dropdownItemRef.value?.toggle();
  state.pageInfo.form = state.searchOptions;
  state.pageInfo.pageIndex = 1;
  state.menberList = [];
  getMemberList()
  state.currentIndex = 0;
  oldSwiperIndex.value = 0;
}
// 精选
const onMoreSearch = () => {
  state.moreSearchWhere = true;
}
// 重置
const onResetSearch = () => {
  state.searchOptions.sex = ''
  state.searchOptions.age = ''
  state.searchOptions.income = ''
  state.searchOptions.educate = ''
  state.searchOptions.height = ''
  state.searchOptions.weight = ''
  state.searchOptions.is_children = ''
  state.searchOptions.want_children = ''
  state.searchOptions.is_house = ''
  state.searchOptions.is_car = ''
  state.searchOptions.province = ''
  state.searchOptions.city = ''
  state.searchOptions.area = ''
  state.searchOptions.marriage = ''
  state.areaValue = ''
}
const dropdownItemRef = ref<DropdownItemInstance>();
onMounted(async () => {
  // 保存推广码分享id
	if (route.query.parent_id) mainStore.parent_id = (route.query.parent_id as string) || null;
  if (mainStore.userInfo == null || mainStore.userInfo.head_img_url == null) {
    console.log('没有用户数据或者用户头像为空');
		return getUserInfo();
	} else {
    if (mainStore.userInfo) {
      console.log('根据用户ID，拉取用户信息');
      const userRes = await memberInfo(mainStore.userInfo.user_id);
      mainStore.userInfo = userRes.data;
      if (userRes.data.head_img_url == null) {
        console.log('拉取的用户信息，头像为空');
        return getUserInfo();
      }
    } else {
      console.log('没有用户信息');
    }
  }
 // 绑定用户关系
	await bindMatchmakerRelate();
});

onActivated( () => {
	if (mainStore.isShare) {
    console.log('是分享');
    refreshMemberInfo()
  }
  else if (state.menberList.length == 0) {
    console.log('无用户数据');
    refreshMemberInfo()
  }
  else {
    console.log('刷新页面');
    const cityInfo = mainStore.cityInfo;
    if (cityInfo == null) {
      //refreshMemberInfo()
    } else {
      if (!mainStore.isUserDetailPath) {
        state.pageInfo.pageIndex = 1;
        state.menberList = [];
        state.active = mainStore.homeTabActive || '同城';
        if (state.active == '栏目认证' || state.active == '全国') {
          cityInfo.city = null;
          cityInfo.province = null;
          cityInfo.country = null;
        }
        updateCityState(cityInfo.city, cityInfo.province, cityInfo.country)
        getMemberList();
      }
    }
  }
});

// 获取用户头像
const getUserHeadImg = (item:any) : string => {
  if (!item.head_img_url) {
    if (!item.user_img) {
      return imgUrl + item.user_img
    } else {
      return imgUrl + item.photo_list[0]
    }
  } else {
    return item.head_img_url
  }
}

// 刷新用户数据
const refreshMemberInfo = async () => {
  console.log('refreshMemberInfo------刷新用户数据',state)
  state.pageInfo.user_id = mainStore.user_id;
  state.pageInfo.pageIndex = 1;
  state.menberList = [];
  await getMemberListBuyCity();
}

// 当前元素
const currentItem = computed<any>(() => state.menberList[state.currentIndex]);

// 绑定推广码红娘关系
const bindMatchmakerRelate = async (): Promise<void> => {
	if (!mainStore.parent_id) return;
	const open_id = mainStore.userInfo.open_id || mainStore.userInfo.openid;
	await bindUserRelate(open_id, mainStore.parent_id);
};

// 获取用户信息
const getUserInfo = async (): Promise<void | string> => {
	const code = getQueryString('code');
	if (!code) return useAuthorize();
  const res = await opendIdByCode(code);
  const cityInfo = mainStore.cityInfo;
  console.log('cityInfo：',cityInfo);
	if (res.errorCode == 0) {
    console.log('授权用户信息已存在');
		const userRes = await memberInfo(res.data.userInfo.id);
		if (userRes.data) {
			mainStore.userInfo = userRes.data;
		} else {
			mainStore.userInfo = res.data.userInfo;
		}
		await bindMatchmakerRelate();
    setTimeout(async ()=>{
      if (cityInfo == null) {
        getMemberListBuyCity().catch((err) => console.log(err));
      } else {
        state.active = '同城';
        updateCityState(cityInfo.city,cityInfo.province,cityInfo.country)
      }
      const userRes = await editUser(formUserData(res.data.openid));
      mainStore.userInfo = userRes.data;
    },1000)
	}
	else if (res.errorCode == 1) {
    console.log('授权失败');
		return useAuthorize();
	}
	else {
    console.log('授权用户信息不存在');
    setTimeout(async ()=>{
      if (cityInfo == null) {
        getMemberListBuyCity().catch((err) => console.log(err));
      } else {
        state.active = '同城';
        updateCityState(cityInfo.city,cityInfo.province,cityInfo.country)
      }
      const userRes = await addUser(formUserData(res.data.openid));
      mainStore.userInfo = userRes.data;
      await bindMatchmakerRelate();
    },1000)
  }
};

const formUserData = (data:any):any => {
  const { openid, nickname, headimgurl, country, province, sex } = data;
  return {
    parent_id: mainStore.parent_id || '',
    opendId: openid,
    nickName: nickname,
    avatarUrl: headimgurl,
    gender: sex,
    province: state.province,
    city: state.city,
    country: state.country
  };
}

// 定位城市获取列表
const getMemberListBuyCity = async (): Promise<any> => {
  Toast.loading({
    message: '正在定位城市',
    forbidClick: true,
  });
  console.log('获取定位城市信息');
	state.pageInfo.pageIndex = 1;
	state.menberList = [];
  const configRes = await getWxConfig();
  const { appId, timestamp, nonceStr, signature } = configRes.data;
  let jsApiList = ['getLocation'];
  wx.config({
    debug: false,
    appId,
    timestamp,
    nonceStr,
    signature,
    jsApiList
  });
  wx.checkJsApi({
    jsApiList: ['getLocation'],
    success: (res:any) => {
      if (res.checkResult.getLocation == false) {
        console.log('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
        return;
      }
    }
  });
  wx.ready(() => {
    wx.getLocation({
      type: 'wgs84',
      success: async (res: any) => {
        const { latitude, longitude } = res;
        const addressRes = await getAddressByGPS(latitude, longitude);
        const { city, district, province } = addressRes.data.result.address_component;
        state.active = '同城';
        // 保存城市信息
        mainStore.cityInfo = {
          city:city,
          province:province,
          country:district
        }
        updateCityState(city,province,district)
        await getMemberList();
      },
      fail: (res:any) => {
        Toast('定位获取失败，请刷新页面');
        console.info('ready getLocation fail=' + JSON.stringify(res))
        getMemberList();
      },
      complete: (res: any) => {

      }
    });
  });
  wx.error((res:any) => {
    console.log('err', res)
  });
};

// 更新当前城市状态
const updateCityState = (city:string,province:string,district:string) => {
  state.city = city;
  state.province = province;
  state.country = district;
  state.pageInfo.city = city;
  // 设置选择器默认城市
  const city_list: any = areaList.city_list;
  state.areaDefaultCode = Object.keys(city_list).find((key) => {
    return city_list[key] === city;
  });
}

// 性别筛选
const sexMenuChange = (value: DropdownItemOption) => {
	state.pageInfo.pageIndex = 1;
	state.menberList = [];
	getMemberListBuyCity();
};

// 成为vip
const vipPopupRef = ref<InstanceType<typeof vipPopup> | null>(null);
const becomeVip = () => {
	vipPopupRef.value!.showPopup();
};
// 开通vip套餐
const openVipPackage = async (currentPackage: any) => {
	const packageParams = {
		user_id: mainStore.user_id,
		vip_id: currentPackage.id,
		amount: currentPackage.price
	};

	// 创建vip套餐订单
	const res = await createVipOrder(packageParams);
	const oid: number = res.data;
  Toast.loading({
    message: '加载中...',
    forbidClick: true,
  });
	const params: any = await wxVipPay(oid);
	wxApiReady(['chooseWXPay'])
		.then((res) => {
			wx.chooseWXPay({
				timestamp: params.timeStamp, // 支付签名时间戳，注意微信 jssdk 中的所有使用 timestamp 字段均为小写。但最新版的支付后台生成签名使用的 timeStamp 字段名需大写其中的 S 字符
				nonceStr: params.nonceStr, // 支付签名随机串，不长于 32 位
				package: params.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
				signType: params.signType, // 微信支付V3的传入 RSA ,微信支付V2的传入格式与V2统一下单的签名格式保持一致
				paySign: params.paySign, // 支付签名
				success: async (result: object) => {
					// 支付成功后的回调函数
					console.log(result);
					Toast.success('支付成功');
					vipPopupRef.value!.closePopup();
				}
			});
		})
		.catch((err: Error) => console.log(err));
};

// 付费一元
const payOneYuan = async (): Promise<void | ToastOptions> => {
	const like_user_id = currentItem.value.user_id;
  const share_user_id = 0;

	// 单次付费看视频订单
	const res = await createOneYuanOrder(mainStore.user_id, like_user_id, share_user_id);
	if (res.errorCode != 0) return Toast(res.errorInfo);
	const oid: number = res.data;
  Toast.loading({
    message: '加载中...',
    forbidClick: true,
  });
	const params: any = await wxPay(oid);
	wxApiReady(['chooseWXPay'])
		.then((res) => {
			wx.chooseWXPay({
				timestamp: params.timeStamp, // 支付签名时间戳，注意微信 jssdk 中的所有使用 timestamp 字段均为小写。但最新版的支付后台生成签名使用的 timeStamp 字段名需大写其中的 S 字符
				nonceStr: params.nonceStr, // 支付签名随机串，不长于 32 位
				package: params.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
				signType: params.signType, // 微信支付V3的传入 RSA ,微信支付V2的传入格式与V2统一下单的签名格式保持一致
				paySign: params.paySign, // 支付签名
				success: async (result: object) => {
					// 支付成功后的回调函数
					console.log(result);
					state.payShow = false;
					Toast.success('支付成功');
					iframeRefs[currentItem.value.id].play();
					// 添加观看记录
					await saveBrowseRecord(mainStore.user_id, like_user_id);
				}
			});
		})
		.catch((err) => console.log(err));
};

// 视频点击
const videoClick = async (like_user_id: number) => {
  if (typeof mainStore.userInfo.audit_state != 'undefined' && mainStore.userInfo.audit_state != 1) {
    if (mainStore.userInfo.audit_state == 0) return Toast('您的资料正在审核中');
    if (mainStore.userInfo.audit_state == 2) return Toast('您的资料审核未通过');
  } else {
    if (!mainStore.userInfo.identity || mainStore.userInfo.identity == '0') {
      router.push('/registered');
      return;
    }
  }
	// 单次付费看视频支付前的检查
	const res = await checkUserStateByOneYuan(mainStore.user_id, like_user_id);
	if (res.errorCode == 0) {
		// 一元付费弹窗
		state.payShow = true;
	} else if (res.errorCode == 1) {
		iframeRefs[currentItem.value.id].play();
	} else {
		Toast(res.errorInfo);
	}
};

// 头像点击
const avatarClick = (user_id: number): void => {
	router.push({ name: 'memberDetail', query: { user_id, type: 'user' } });
};

// 收藏/取消收藏
const collect = async (like_user_id: number, index: number): Promise<any> => {
  if (typeof mainStore.userInfo.audit_state != 'undefined' && mainStore.userInfo.audit_state != 1) {
    if (mainStore.userInfo.audit_state == 0) return Toast('您的资料正在审核中');
    if (mainStore.userInfo.audit_state == 2) return Toast('您的资料审核未通过');
  } else {
    if (!mainStore.userInfo.identity || mainStore.userInfo.identity == 0) {
      router.push('/registered');
      return;
    }
  }
	const res = await saveCollect(mainStore.user_id, like_user_id);
	Toast(res.errorInfo);
	const { is_collect, like_num } = state.menberList[index];
	const isCollect: boolean = res.data !== 1 ? false : true;
	state.menberList[index].is_collect = isCollect ? 0 : 1;
	state.menberList[index].like_num = isCollect ? like_num - 1 : like_num + 1;
};

// 分享
const initShare = async (update:boolean = false) => {
  const wxConfig = mainStore.wxConfig;
  console.log('wxConfig：',wxConfig)
  if (wxConfig == null || update) {
    const configRes = await getWxConfig();
    mainStore.wxConfig = configRes.data;
  }
  const { appId, timestamp, nonceStr, signature } = mainStore.wxConfig;
  let jsApiList = ['onMenuShareAppMessage', 'onMenuShareTimeline'];
  wx.config({
    debug: false,
    appId,
    timestamp,
    nonceStr,
    signature,
    jsApiList
  });
  wx.ready(() => {
      wx.onMenuShareAppMessage({
        title: siteTitle, // 分享标题
        desc: `我是【${currentItem.value?.username}】，实名相亲，等待牵手。`, // 分享描述
        link: `https://ztcy.huimaibuy.com/h5/#/memberDetail?parent_id=${mainStore.user_id}&user_id=${currentItem.value.user_id}&type=user&share_user_id=${mainStore.user_id}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
        imgUrl: currentItem.value.head_img_url, // 分享图标
        type: 'link', // 分享类型,music、video或link，不填默认为link
        dataUrl: '', // 如果 type 是music或video，则要提供数据链接，默认为空
        success: async () => {
          // 用户点击了分享后执行的回调函数
          // 更新转发数量
          const res = await updateShareCount(currentItem.value.user_id);
          console.log(res);
        },
        cancel: (res: any) => {
          console.log(res);
        }
      });
      wx.onMenuShareTimeline({
        title: siteTitle, // 分享标题
        link: `https://ztcy.huimaibuy.com/h5/#/memberDetail?parent_id=${mainStore.user_id}&user_id=${currentItem.value.user_id}&type=user&share_user_id=${mainStore.user_id}`,
        imgUrl: currentItem.value.head_img_url, // 分享图标
        success: async () => {
          // 用户点击了分享后执行的回调函数
          // 更新转发数量
          const res = await updateShareCount(currentItem.value.user_id);
          console.log(res);
        },
        cancel: (res: any) => {
          console.log(res);
        }
      });
  });
  wx.error((res:any) => {
    console.log('err', res)
  });
};

// 拨打电话
const callMobile = (mobile: string): any => {
  if (typeof mainStore.userInfo.audit_state != 'undefined' && mainStore.userInfo.audit_state != 1) {
    if (mainStore.userInfo.audit_state == 0) return Toast('您的资料正在审核中');
    if (mainStore.userInfo.audit_state == 2) return Toast('您的资料审核未通过');
  }
  if (!mainStore.userInfo.identity || mainStore.userInfo.identity == 0) {
    return Toast('成为平台会员后可查看联系方式');
  } else {
	  state.mobile = `tel:${mobile}`;
  }
};

// 视频组件dom列表
interface IIframeRefs {
	[key: number | string]: any;
}
let iframeRefs: IIframeRefs = {};
const setItemRef = (el: Element | ComponentPublicInstance | null, key: number | string) => {
	if (el) {
		iframeRefs[key] = el;
	}
};

// swiper 切换
let oldSwiperIndex = ref<number>(0);
let timer: NodeJS.Timeout | null = null;
const onSlideChange = (e: SwiperClass) => {
  console.log(iframeRefs)
	if (timer) {
		clearTimeout(timer);
		timer = null;
	}

	// 防抖 切换tab 认证会员弹窗弹出 / initShare()频繁调用问题
	timer = setTimeout(() => {
		if (e.activeIndex >= 3 && state.showFlag && state.active === '栏目认证') {
			state.vipShow = true;
			state.showFlag = false;
		}
		// 加载更多
		if (e.activeIndex + 1 == state.menberList.length) {
			getMemberList();
		}
		state.currentIndex = e.activeIndex;

		// 重新加载当前视频
		if (currentItem.value && currentItem.value?.vcr.video_url) {
			nextTick(() => {
				iframeRefs[currentItem.value.id].videoRef.load();
			});
		}

		// 暂停上条视频
		const pvreItem = state.menberList[oldSwiperIndex.value];
		if (pvreItem && pvreItem.vcr.video_url) {
			nextTick(() => {
				iframeRefs[pvreItem.id].videoRef.pause();
			});
		}
		oldSwiperIndex.value = e.activeIndex;

		initShare();
	}, 500);
};

// 选择城市确认
const areaConfirm = (result: AreaColumnOption[]) => {
  console.log(result);
	state.pageInfo.pageIndex = 1;
	state.menberList = [];
	state.pageInfo.is_vip_video = null;
	state.pageInfo.province = result[0].name;
	state.pageInfo.city = result[1].name;
  if (result[1].name != '') {
    state.currentCity = state.pageInfo.city;
  } else {
    state.currentCity = state.pageInfo.province;
  }
	getMemberList();
	state.active = '同城';
	state.areaShow = false;
};

// tab切换
const tabsBeforeChange = (name: number | string): boolean => {
  mainStore.homeTabActive = name;
	state.pageInfo.pageIndex = 1;
	state.menberList = [];
	if (name === '全国') {
		state.pageInfo.city = '';
		state.pageInfo.is_vip_video = null;
		getMemberList();
	} else if (name === '同城') {
		state.pageInfo.is_vip_video = null;
		getMemberListBuyCity();
	} else {
    state.pageInfo.city = '';
		state.pageInfo.is_vip_video = 1;
		getMemberList();
	}
	state.currentIndex = 0;
	oldSwiperIndex.value = 0;
	return true;
};

// 获取用户列表
const getMemberList = async () => {
  console.log('拉取用户并重置wx-js-api配置');
  Toast.loading({
    message: '正在加载用户中',
    forbidClick: true,
  });
	const res = await memberList(state.pageInfo);
	if (res.data.dataList.length) {
		state.menberList = [...state.menberList, ...res.data.dataList];
		state.pageInfo.pageIndex++;
		await initShare(false);
	}
};
</script>

<style lang="scss" scoped>
:deep(.van-field) {
  .van-field__control--custom {
    justify-content: flex-end;
  }
}

:deep(.van-tabs) {
	width: 100%;
	.van-tabs__wrap {
		height: 50px !important;
		.van-tabs__nav {
			justify-content: space-between;
			.van-tab {
				flex: auto;
				padding: 0;
				font-size: 16px;
			}
			.van-tab--active {
				font-size: 17px;
				font-weight: bold;
			}
		}

		.van-tabs__line {
			bottom: 20px;
			background: #f6438a;
		}
	}
}

:deep(.van-dropdown-menu) {
	.van-dropdown-menu__bar {
		box-shadow: none;
		background: white;
		.van-dropdown-menu__title {
			color: #f54386;
			font-size: 13px;
			&::after {
				border-color: transparent transparent #f54386 #f54386;
			}
		}
	}
	.van-popup--top {
		border-radius: 0 0 15px 15px;
	}
  .van-dropdown-item__content {
    max-height: 100%;
  }
}

:deep(.van-radio) {
  .van-radio__icon--checked .van-icon {
    background-color:#f54386;
    border-color:#f54386;
  }
}

.home {
	padding: 0 15px;
	.header {
		@include flx-justify-between;
		height: 60px;
		.city {
			@include flx-align-center;
			height: 100%;
			span {
				font-size: 13px;
				margin-left: 2px;
			}
			.play {
				transform: rotate(90deg);
			}
		}
		.tabs {
			@include flx-center;
			height: 100%;
			width: 190px;
		}
	}
}
</style>
